<template>
  <div class="type-wrap">
    <div class="btn-group">
      <el-button type="primary" icon="el-icon-circle-plus" @click="addUser">添加用户组</el-button>
      <el-button icon="el-icon-refresh" @click="refresh">刷新</el-button>
    </div>
    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" align="center" label="ID" width="80" sortable></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="80">
        <template slot-scope="scope">
          <i class="size24" :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column prop="title" align="center" label="中文名称" width="160" sortable></el-table-column>
      <el-table-column prop="name" align="center" label="标识" sortable width="100"></el-table-column>
      <el-table-column prop="remark" label="说明"></el-table-column>
      <el-table-column prop="status" label="状态" align="center" sortable width="100">
        <template slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.status == 'Normal'"></i>
          <i class="el-icon-error" v-else></i>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="180">
        <template slot-scope="scope">
          <i @click="handleEdit(scope.$index, scope.row)" class="el-icon-edit colorBrand size23"></i>
          <i
            @click="handleDelete(scope.$index, scope.row)"
            class="el-icon-delete colorBrand size23"
          ></i>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="添加用户组" :visible.sync="addUserType" :close-on-click-modal="false">
      <el-form :model="userFore" :rules="rules" ref="addForm" label-width="110px">
        <el-form-item label="中文名称" prop="title" >
          <el-input v-model="userFore.title" type="string"></el-input>
        </el-form-item>
        <el-form-item label="标识" prop="name">
          <el-input v-model="userFore.name " type="string"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <icon-select @selected="selectedIcon"></icon-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="userFore.sort" ></el-input>
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="userFore.remark"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="userFore.status" :value="userFore.status" placeholder="请选择状态">
            <el-option label="启用" value="Normal"></el-option>
            <el-option label="禁用" value="Fail"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserType = false">取 消</el-button>
        <el-button type="primary" @click="RoleType('addForm')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户" :visible.sync="editUser">
      <el-form :model="userFore" :rules="rules" ref="editForm" label-width="121px">
        <el-form-item label="中文名称" prop="title" >
          <el-input v-model="userFore.title" type="string"></el-input>
        </el-form-item>
        <el-form-item label="标识"  prop="name">
          <el-input v-model="userFore.name " type="string"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <icon-select @selected="selectedIcon"></icon-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="userFore.sort" ></el-input>
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="userFore.remark"></el-input>
        </el-form-item>
        <el-form-item label="用户组分类标识">
          <el-select v-model="userFore.guard_name" :value="userFore.guard_name" placeholder="请选择状态">
            <el-option label="用户" value="User"></el-option>
            <el-option label="后台管理" value="Admin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="userFore.status" :value="userFore.status" placeholder="请选择状态">
            <el-option label="启用" value="Normal"></el-option>
            <el-option label="禁用" value="False"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="editUser = false">取 消</el-button>
        <el-button type="primary" @click="RoleType('editForm')">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { constants } from "crypto";
import IconSelect from "../../../components/IconSelect";
import { setTimeout } from 'timers';
export default {
  name: "Type",
  data() {
    return {
      addUserType: false,
      editUser: false,
      userFore: {
        title: "",
        icon: "",
        module_id: 1,
        remark: "",
        status: "Normal",
        sort: 0
      },
      rules:{
        title: [{ required: true, validator: titleValiData, trigger: 'change' }],
        name: [{ required: true, validator: nameValiData, trigger: 'change' }],
        sort:[{ required: true, validator: sortValiData, trigger: 'change' }],
      },
      tableData: []
    };
  },
  created: function() {
    // console.group("------created创建完毕状态------");
    this.init();
  },
  methods: {
    init() {
      axios
        .get("/api/v1/role/type/list")
        .then(result => {
          this.tableData = result.data.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    handleEdit(e) {
      this.userFore = this.tableData[e];
      this.editUser = true;
    },
    handleDelete(e) {
      this.$confirm("是否删除此用户组?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let id = this.tableData[e].id;
          axios
            .get("/api/v1/role/type/delete/" + id)
            .then(result => {
              if (result.data.code == 200) {
                this.$message({
                  type: "success",
                  message: result.data.message
                });
                this.init();
              }
            })
            .catch(error => {
              this.$message({
                type: "error",
                message: "错误"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    selectedIcon(e) {
      this.userFore.icon = e;
    },
    addUser(){
      this.addUserType = true;
      this.deleteValue();
    },
    notice(index, str) {
      switch (index) {
        case "error":
          this.$message({
             dangerouslyUseHTMLString: true,
            message: str,
            type: "error"
          });
          break;
        case "success":
          this.$message({
            message: str,
            type: "success"
          });
          
          break;
        case "warning":
          this.$message({
            message: str,
            type: "warning"
          });
          break;
        default:
          this.$message(str);
          break;
      }
    },
    deleteValue() {
      let userFore = this.userFore;
        userFore = {
          title: null,
          remark: null,
          status: 'Normal',
          module_id: 1,
          icon: null,
          name: null,
          sort: 0,
          guard_name: 'User'
        }
        this.userFore =userFore 
    },
    RoleType(formName) {
      console.log(formName)
        this.$refs[formName].validate((valid) => {
          if(formName == "addForm"){
            if (valid) {
            axios
            .post("/api/v1/role/type/create", {
              title: this.userFore.title.trim(),
              name: this.userFore.name.trim(),
              module_id: this.userFore.module_id,
              icon: this.userFore.icon,
              sort: this.userFore.sort,
              remark: this.userFore.remark,
              status: this.userFore.status,
              guard_name: this.userFore.guard_name
            })
            .then(result => {
              if (result.data.code == 200) {
                this.init();
                this.addUserType = false;
                this.notice('success', result.data.message);
              }
            })
            .catch(error => {
              let str = '';
              Object.keys(error.response.data.message).forEach((index)=>{
                str+=error.response.data.message[index][0]+ '<br >';
              });
              this.notice('error', str);
            });
            } else {
              console.log('error submit!!');
              return false;
            }
          }else {
            if (valid) {
            let id = this.userFore.id;
            axios
            .post("/api/v1/role/type/edit/" + id, {
              title: this.userFore.title,
              name: this.userFore.name,
              module_id: this.userFore.module_id,
              icon: this.userFore.icon || 'fas el-icon-plus',
              sort: this.userFore.sort,
              remark: this.userFore.remark,
              status: this.userFore.status,
              guard_name: this.userFore.status
            })
            .then(result => {
              if (result.data.code == 200) {
                this.init();
                this.editUser = false;
                this.notice('success', result.data.message);
              } else {
                this.notice('error', result.data.message);
            }
          }).catch(error => {
            let str = '';
              Object.keys(error.response.data.message).forEach((index)=>{
                str+=error.response.data.message[index][0]+ '<br >';
              });
              this.notice('error', str);
          });

          } else {
            console.log('error submit!!');
            return false;
          }
          }
        }
        );
      },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    refresh(){
      this.init();
      this.notice('success',"刷新成功")
    }
  },
  components: {
    IconSelect
  },
  
};
export function titleValiData (rule, value, callback) {
  const reg = /^[\u4e00-\u9fa5]+$/
  if (!value) {
    return callback(new Error('请填写用户名'))
  } else if (!reg.test(value)) {
    return callback(new Error('用户名格式错误'))
  } else {
    callback()
  }
}
export function nameValiData (rule, value, callback) {
  const reg = /^[a-zA-Z0-_-\-]+$/
  if (!value) {
    return callback(new Error('请填写标识'))
  } else if (!reg.test(value)) {
    return callback(new Error('标识格式错误'))
  } else {
    callback()
  }
}

export function sortValiData (rule, value, callback) {
  const reg = /^[0-9]*$/;
  if(value === 0){
    callback()
  }else {
      if (!value) {
      return callback(new Error('请填写排序'))
    } else if (!reg.test(value)) {
      return callback(new Error('排序必须为数字'))
    } else {
      callback()
    }
  }
  
};
</script>
<style scoped>
.colorBrand {
  color: #409eff;
}
</style>